package com.tegtech.starter.feign.config;

import java.util.concurrent.TimeUnit;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.Contract;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import feign.hystrix.HystrixFeign;
import okhttp3.ConnectionPool;

/**
 * Feign配置
 * @Author Jun
 */
@EnableFeignClients("com.tegtech.**.feign")
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignConfig {
	
	private static final int feignOkHttpReadTimeout = 10;
	private static final int feignConnectTimeout = 5;
	private static final int feignWriteTimeout = 10;
	private static final int maxIdleConnections = 20;
	private static final long keepAliveDuration = 10L;

//    @Bean
//    public OkHttpClient okHttpClient(){
//        return new OkHttpClient.Builder()
//                .readTimeout(60, TimeUnit.SECONDS)
//                .connectTimeout(60, TimeUnit.SECONDS)
//                .writeTimeout(120, TimeUnit.SECONDS)
//                .connectionPool(new ConnectionPool())
//                .build();
//    }
	
	@Bean
	public okhttp3.OkHttpClient okHttpClient() {
		return new okhttp3.OkHttpClient.Builder()
				// 读超时时间配置
				.readTimeout(feignOkHttpReadTimeout, TimeUnit.SECONDS)
				// 连接超时时间配置
				.connectTimeout(feignConnectTimeout, TimeUnit.SECONDS)
				// 写超时时间配置
				.writeTimeout(feignWriteTimeout, TimeUnit.SECONDS)
				// 连接失败是否重试
				.retryOnConnectionFailure(true)
				// 自定义连接池配置
				.connectionPool(new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.MINUTES))
				.build();
	}

    @Bean
    public Feign.Builder feignBuilder() {
    	return HystrixFeign.builder();
    }

    @Bean
    public Contract feignContract() {
        return new SpringMvcContract();
    }

    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public Request.Options feignRequestOptions() {
        return new Request.Options(10, TimeUnit.SECONDS, 60, TimeUnit.SECONDS, true);
    }

    @Bean
    public Retryer feignRetry() {
//        return new Retryer.Default();
        return new Retryer.Default(100, 1000, 3);
    }

}